import { listPhoto } from '@/api/content/photos';
import { Button, Col, DatePicker, Form, Image, Row, Space, Spin } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import AddPhoto from './addPhoto';
import styles from './index.module.less';

const Photo = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false); // 加载状态
  const [isOpen, setIsOpen] = useState(false); // 是否打开弹窗
  const [activeData, setActiveData] = useState(null); // 当前操作的数据
  const [type, setType] = useState('year'); // 时间类型
  const [photoData, setPhotoData] = useState({}); // 数据列表

  // 搜索
  const handleSearch = () => {
    getList(1);
  };
  // 重置
  const handleReset = () => {
    form.resetFields();
    getList();
  };

  // 新增
  const changeOpen = (val, data) => {
    setIsOpen(val);
    setActiveData(data);
    if (!val) {
      getList();
    }
  };

  // 获取数据
  const getList = async () => {
    const values = form.getFieldsValue();
    const data = {
      attributionTime:
        type === 'year' ? dayjs(values.year).format('YYYY') + '-01' : dayjs(values.month).format('YYYY-MM'),
      pageNum: 1,
      pageSize: 500,
      type: type,
    };
    setLoading(true);
    const res = await listPhoto(data);
    if (res.code === 200) {
      const classifiedItems = res.data.rows.reduce((acc, item) => {
        // 如果当前 name 不在累加器中，则初始化为一个新数组
        if (!acc[item.attributionTime]) {
          acc[item.attributionTime] = [];
        }
        // 将当前项添加到对应 name 的数组中
        item.photoList = item.photoPath.split(',');
        if (item.photoList.length > 3) {
          const newList = item.photoList.map((i) => {
            return {
              ...item,
              photoList: i,
            };
          });
          acc[item.attributionTime] = [...acc[item.attributionTime], ...newList];
        } else {
          acc[item.attributionTime].push(item);
        }

        // 返回累加器以供下一次迭代
        return acc;
      }, {});
      setPhotoData(classifiedItems);
    }
    setLoading(false);
  };

  const onChange = (type) => {
    setType(type);
    if (type === 'year') {
      form.setFieldsValue({ month: undefined });
    } else {
      form.setFieldsValue({ year: undefined });
    }
  };

  useEffect(() => {
    form.setFieldsValue({ year: dayjs(new Date()) });
    getList();
  }, []);
  return (
    <div className='viewBox'>
      <Form form={form}>
        <Row className={styles.btnBox}>
          <Col span={6}>
            <Form.Item name='month' label='月份' className='searchItem'>
              <DatePicker onChange={() => onChange('month')} picker='month' dateFormat='yyyy-mm' allowClear={false} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name='year' label='年份' className='searchItem'>
              <DatePicker onChange={() => onChange('year')} picker='year' dateFormat='yyyy' allowClear={false} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Space wrap>
              <Button type='primary' onClick={handleSearch}>
                查询
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
      <div className='btnBox'>
        <Space wrap>
          <Button type='primary' onClick={() => changeOpen(true)}>
            新增
          </Button>
        </Space>
      </div>
      {loading ? (
        <div
          className={styles.photoBox}
          style={{ height: '200px', display: 'flex', justifyContent: 'center', alignItems: 'center' }}
        >
          <Spin />
        </div>
      ) : (
        <div className={styles.photoBox}>
          {Object.keys(photoData).map((key) => (
            <div key={key} className={styles.todayBox}>
              <div className={styles.date}>{key}</div>
              {photoData[key]?.map((i) => (
                <div key={i.photoId} className={styles.rows}>
                  {i.photoList.map((j) => (
                    <Image width={100} src={j} key={j} />
                  ))}
                </div>
              ))}
            </div>
          ))}
        </div>
      )}

      {isOpen && <AddPhoto isOpen={isOpen} changeOpen={changeOpen} setIsOpen={setIsOpen} activeData={activeData} />}
    </div>
  );
};

export default Photo;
